<template>
    <el-row class="row-top" type="flex" align="middle">
        <el-col :span="6">
            <el-row type="flex" justify="center" align="middle">
                <el-col :span="8"></el-col>
                <el-col :span="6"></el-col>
                <el-col :span="10" class="userInfoLeft">头像:</el-col>
            </el-row>
        </el-col>
        <el-col :span="10">
            <el-avatar :size="60" @error="errorHandler">
                <img :src="userAvatarPath"/>
                <div class="mask iconfont icon-xiangji" @click="changeAvatar"></div>
            </el-avatar>
        </el-col>
        <el-col :span="8"></el-col>
    </el-row>
    <el-row>
        <el-col :span="6">
            <el-row type="flex" justify="center" align="middle">
                <el-col :span="8"></el-col>
                <el-col :span="6"></el-col>
                <el-col :span="10" class="userInfoLeft">昵称:</el-col>
            </el-row>
        </el-col>
        <el-col :span="10">
            <el-input v-model="userInfo.nickName"></el-input>
        </el-col>
        <el-col :span="8"></el-col>
    </el-row>
    <el-row>
        <el-col :span="6">
            <el-row type="flex" justify="center" align="middle">
                <el-col :span="8"></el-col>
                <el-col :span="6"></el-col>
                <el-col :span="10" class="userInfoLeft">我的签名:</el-col>
            </el-row>
        </el-col>
        <el-col :span="10">
            <el-input
                v-model="userInfo.personalizedSignature"
                :rows="2"
                type="textarea"
                placeholder="请输入您的个性签名"
            />
        </el-col>
        <el-col :span="8"></el-col>
    </el-row>
    <el-row>
        <el-col :span="6">
            <el-row type="flex" justify="center" align="middle">
                <el-col :span="8"></el-col>
                <el-col :span="6"></el-col>
                <el-col :span="10" class="userInfoLeft">性别:</el-col>
            </el-row>
        </el-col>
        <el-col :span="10">
            <el-radio-group v-model="userInfo.sex">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
                <el-radio :label="2">阿帕奇武装直升机</el-radio>
            </el-radio-group>
        </el-col>
        <el-col :span="8"></el-col>
    </el-row>
    <el-row>
        <el-col :span="6">
            <el-row type="flex" justify="center" align="middle">
                <el-col :span="8"></el-col>
                <el-col :span="6"></el-col>
                <el-col :span="10" class="userInfoLeft">出生日期:</el-col>
            </el-row>
        </el-col>
        <el-col :span="10">
            <el-date-picker
                v-model="userInfo.birthday"
                type="date"
                placeholder="Pick a day"
                :size="size"
            />
        </el-col>
        <el-col :span="8"></el-col>
    </el-row>
    <el-divider/>
    <el-row>
        <el-col :span="8"></el-col>
        <el-col :span="8">
            <el-row type="flex" justify="center">
                <el-button type="primary" style="width:6vw" @click="saveUserInfo">保存</el-button>
            </el-row>
        </el-col>
        <el-col :span="8"></el-col>
    </el-row>
    <!-- 这里是头像弹框 -->
    <el-dialog v-model="centerDialogVisible" title="上传头像" width="30%" destroy-on-close center>
        <div>
            <div v-if="avatarShow">
                <input type="file" @change="croppingAvatar"/>
            </div>
            <div v-show="avatarShow == false" class="croppingAvatar">
                <div class="croppingAvatarSon">
                    <div style="width: 50%;height: 100%;">
                        <VuePictureCropper
                            :boxStyle="{
                width: '100%',
                height: '100%',
                backgroundColor: '#f8f8f8',
                margin: 'auto',
              }"
                            :img="imgSrc"
                            :options="{
                viewMode: 1,
                dragMode: 'crop',
                aspectRatio: 16 / 16,
              }"
                        />
                    </div>
                    <div v-if="result.dataURL">
                        <div
                            style="width:15vh;height:15vh;border-radius: 7.5vh;overflow: hidden;display: inline-block;position: relative;top:-17vh;left:17vw"
                        >
                            <img
                                :src="result.dataURL"
                                title="裁剪之后头像"
                                class="afterCut"
                                style="height:100%;width:100%"
                            />
                        </div>
                    </div>
                </div>
                <div class="croppingAvatarSon">
                    <el-button @click="avatarShow = true">取消</el-button>
                    <el-button @click="clear">清除</el-button>
                    <el-button @click="reset">重置</el-button>
                    <el-button @click="getResult">裁切</el-button>
                </div>
            </div>
        </div>
        <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="uploadImage">确认</el-button>
      </span>
        </template>
    </el-dialog>
</template>
<script>
import {computed, defineComponent, onMounted, reactive, ref, watch} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import VuePictureCropper, {cropper} from "vue-picture-cropper";
import RequestUtil from "@/utils/RequestUtil.js";
import InfoUtil from "@/utils/InfoUtil.js";
import StringUtil from "@/utils/StringUtil.js";

let reader = new FileReader();
let imageURL = null;
reader.addEventListener(
    "load",
    () => {
        imageURL = reader.result;
    },
    false
);
export default defineComponent({
    components: {
        VuePictureCropper
    },
    setup() {

        let store = useStore();
        let router = useRouter();

        onMounted(()=>{
            store.state.user.user
        })

        let userAvatarPath = computed(() => {
            return store.state.user.userAvatarPath;
        });
        let userInfoForCopy = computed(() => {
            return store.state.user.user;
        });
        let userInfo = reactive({
            nickName: "",
            personalizedSignature: "",
            birthday: "",
            sex: ""
        });
        watch(
            () => {
                store.state.user.user;
            },
            () => {
                for (const key in userInfo) {
                    if (userInfoForCopy.value[key] === undefined || userInfoForCopy.value[key] === null) {
                        userInfo[key] = null;
                    } else {
                        userInfo[key] = userInfoForCopy.value[key];
                    }
                }
            },
            {immediate: true, deep: true}
        );
        let centerDialogVisible = ref(false);
        // 初始化是否展示选择图片的dom
        let avatarShow = ref(true);
        let imgSrc = ref("");
        let result = reactive({
            dataURL: ""
        });
        const changeAvatar = () => {
            centerDialogVisible.value = true;
        };
        // 上传之前进行的操作
        const croppingAvatar = file => {
            // 重置上一次的数据
            result.dataURL = "";
            avatarShow.value = false;
            reader.readAsDataURL(file.target.files[0]);
            reader.onload = () => {
                setTimeout(() => {
                    imgSrc.value = imageURL;
                }, 0);
            };
        };
        const clear = () => {
            cropper.clear();
        };
        const reset = () => {
            cropper.reset();
        };
        const getResult = () => {
            // 获取生成的base64图片地址
            // 把base64赋给结果展示区
            result.dataURL = cropper.getDataURL();
        };
        const base64ToFile = (base64, fileName) => {
            let dataArr = base64.split(",");
            let byteString = atob(dataArr[1]);
            let options = {
                type: "image/png",
                endings: "native"
            };
            let u8Arr = new Uint8Array(byteString.length);
            for (let i = 0; i < byteString.length; i++) {
                u8Arr[i] = byteString.charCodeAt(i);
            }
            return new File([u8Arr], fileName + ".png", options);
        };
        const uploadImage = () => {
            let fileInfo = base64ToFile(result.dataURL, "头像图片");
            RequestUtil.sendPostRequestUploadImg("/file/uploadUserAvatar", {
                img: [fileInfo]
            }).then(
                response => {
                    if (response.code != 200) {
                        InfoUtil.warning(response.message);
                        return
                    }
                    window.location.reload()
                },
                err => {
                    console.log(err);
                    InfoUtil.error("上传图片失败");
                }
            );
        };
        const saveUserInfo = () => {
            if (StringUtil.isEmpty(userInfo.nickName)) {
                InfoUtil.warning("昵称不能为空");
                return
            }
            if (userInfo.nickName.length > 20 || userInfo.nickName.length < 1) {
                InfoUtil.warning("昵称长度不符合要求");
                return
            }
            if (userInfo.personalizedSignature.length > 200) {
                InfoUtil.warning("签名长度超出最大限制");
                return
            }
            RequestUtil.sendPostRequest("/user/updateInfo", userInfo).then(
                res => {
                    if (res.code != 200) {
                        InfoUtil.error(res.message);
                        return;
                    }
                    InfoUtil.success(res.message);
                    window.location.reload()
                },
                err => {
                    InfoUtil.error("请求失败");
                }
            );
        };
        return {
            centerDialogVisible, avatarShow, imgSrc, result, userAvatarPath, userInfo, userInfoForCopy,
            changeAvatar, croppingAvatar, clear, reset, getResult, uploadImage, base64ToFile, saveUserInfo,
        };
    }
});
// 1111
</script>
<style lang="scss" scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}

.clickToUpload button:first-child {
    width: 27vw;
    height: 20vh;
    background-color: rgb(242, 242, 242);
    border: 1px dashed rgb(221, 221, 221);

    .icon-shangchuan {
        font-size: 2rem;
        color: rgb(153, 153, 153);
    }
}

.croppingAvatar {
    width: 27vw;
    height: 20vh;

    .croppingAvatarSon:nth-child(1) {
        width: 100%;
        height: 87%;
    }

    .croppingAvatarSon:nth-child(2) {
        height: 10%;
        width: 50%;
        margin-top: 2vh;

        .el-button {
            width: 20%;
        }
    }
}

.el-row {
    margin-bottom: 2vh;
}

.row-top {
    margin-top: 3vh;
    height: 8vh;

    .el-avatar {
        width: 8vh;
        height: 8vh;
        position: relative;

        .mask {
            width: 100%;
            height: 100%;
            border-radius: 4vh;
            background-color: grey;
            opacity: 0;
            position: absolute;
            text-align: center;
            line-height: 8vh;
            font-size: 2.5rem;
        }

        .mask:hover {
            width: 100%;
            height: 100%;
            border-radius: 4vh;
            background-color: grey;
            opacity: 0.7;
            position: absolute;
            text-align: center;
            line-height: 8vh;
            font-size: 2.5rem;
        }
    }
}

.userInfoLeft {
    text-align: right;
    padding-right: 1vw;
}

</style>
